<?php

namespace app\home\controller;

use app\home\service\NotifyService;
use app\home\service\OrderService;
use app\tools\BillingPoint;
use Exception;
use think\Request;
use think\Config;

class Order800005 extends BasePay
{

    public function __construct()
    {
        parent::__construct();
        set_cors();
    }

    public function test(){
        var_dump(2234);
        $redis = new \Redis();
        $redis->connect(config('REDIS_FORMAL.host'), config('REDIS_FORMAL.port'));
        $redis->auth(config('REDIS_FORMAL.auth'));
        $res = $redis->select(0);
        var_dump($res);die;
    }

    //iso 提审 没做那么多效验 
    public function ios_order(){
        try{
            $params = Request::instance()->param();
            $UserID = $params['userid'];
            $GoodsID = $params['stroeid'];
            $Channel = $params['channel'];
    
            $Account = db('accounts_info','db_operatelog_ios')->where("UserID",$UserID)->find();
    
            $BillingPoint = BillingPoint::getBillingPointById($GoodsID);
            if($BillingPoint === false){
                return false;
            }
            $OrderId = get_microtimes();
            $data = [
                'id' => $OrderId,
                'userid' => $UserID,
                'goods_id' => $GoodsID,
                'goods_name' =>$BillingPoint['Title'],
                'amount' => $BillingPoint['Price'],
                'status' => 0, //默认是0,表示未付款
                'channel_id' => $Channel,
                'SpreaderID' => $Account['SpreaderID'],
                'createdat' => date('Y-m-d H:i:s'),
                'registerat' => $Account['RegisterDate'],
                'loginIp' => get_client_ip()
            ];
            $res = db('tradelog','db_operatelog_ios')->insert($data);
            if ($res == false) {
                return false;
            }
    
            $return['order_id'] = $OrderId;
            $return['amount'] = $BillingPoint['Price'];
            $return['goods_id'] = $GoodsID;
            $return['goods_name'] = $BillingPoint['Title'];
            $data_Arr['code'] = 'success';
            $data_Arr['data'] = $return;
            putsuccess($data_Arr);
        }catch(\Exception $exception){
            mylog('800005-ios_order-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return false;
        }
    }
    //ios 提审
    public function ios_notify(){
        $params = Request::instance()->param();
        mylog($params);
        try{
            $html = $this->acurl(str_replace(' ',"+", $params['receiptData']), 1);
            $data = json_decode($html,true);
            if($data['status'] != 0){
                throw new Exception('苹果返回失败');
            }
            $tradelog = db('tradelog','db_operatelog_ios')->where(['id'=>$params['order_id']])->find();
            if(!$tradelog){
                throw new Exception('未找到订单');
            }
            
            //判断计费点
            if(empty($data['receipt']['in_app'][0]['product_id'])){
                throw new Exception('苹果返回product_id未找到');
            }
            

            $product_id = $data['receipt']['in_app'][0]['product_id'];
            $product_data = explode('_',$product_id);
            $product_id = $product_data[1];
            //效验金额
            $CfgIOS = BillingPoint::CfgIOS($product_id);
            if(!$CfgIOS){
                throw new Exception('未找到改product_id配置信息');
            }
            $OddPrice = $CfgIOS['OddPrice'];

            if ($OddPrice != $tradelog['amount']){
                throw new Exception('订单金额和配置金额不一致');
            }
            if ($tradelog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800004 ios_notify 订单已经处理过了 订单id".$tradelog['id']);
                exit(json_encode(['code'=>1,'msg'=>'']));
            }
            db('tradelog','db_operatelog_ios')->where(['id'=>$params['order_id']])->update([
                'transactionID'=>$data['receipt']['in_app'][0]['transaction_id'],
                'status'=>1
            ]);
            //修改用户数据
            $accounts_info = db('accounts_info','db_operatelog_ios')->where(['UserID'=>$tradelog['userid']])->find();

            $level = vip_level($accounts_info['TotalRecharge']+$OddPrice);   //充值后对应等级
            if ($level >= 2) {
                $VipLevel =  $level;
            }else{
                //业务需要--不该配置-当充值金额小于68的都给68 vip 等级为2
                $VipLevel =  2;
            }
            if($accounts_info['TotalRecharge']+$OddPrice >=68){
                $TotalRecharge = $accounts_info['TotalRecharge']+$OddPrice;
            }else{
                $TotalRecharge = 68;
            }

            $updateUserData= [
                'ChargeScore'=>$accounts_info['ChargeScore']+$OddPrice,
                'TotalRecharge'=>$TotalRecharge,
                'RechargeTimes'=>$accounts_info['RechargeTimes']+1,
                'SMoney'=>$accounts_info['TotalRecharge']+$OddPrice*10,
                'VipLevel'=>$VipLevel,
            ];
            db('accounts_info','db_operatelog_ios')->where(['UserID'=>$tradelog['userid']])->update($updateUserData);
            //发货
            $cannon = db('user_game_info','db_operatelog_ios')->where('UserID', $tradelog['userid'])->value('Cannon');

            $accounts_info_send = db('accounts_info','db_operatelog_ios')->where(['UserID'=>$tradelog['userid']])->find();
            $data = [
                'Type' => 1000,
                'RechargeStock' => 0,
                'Award' => [],
                'UserID' => (int)$tradelog['userid'],
                'Cannon' => (int)$cannon,
                'Score' => (int)$accounts_info_send['Score'],
                'Diamond' => (int)$accounts_info_send['Diamond'],
                'GoodsID' => (int)$tradelog['goods_id'],
                'channel_id' => (int)$tradelog['channel_id'],
                'amount' => (int)$tradelog['amount'],
                'SMoney' => (int)$accounts_info_send['SMoney'],
                'Recharge' => (int)$accounts_info_send['TotalRecharge'],
                'VipLevel' => (int)$accounts_info_send['VipLevel'],
            ];
            $url_param = json_encode($data);
            $url = 'http://172.17.43.180:10000/?id=1&data=' . $url_param;
            serverLog($url);
            $res = curl_get($url);
            if ($res === false || $res != 'success') {
                serverLog('调用结果:'.$res );
                throw new Exception('发货失败');
            }
            exit(json_encode(['code'=>1,'msg'=>'']));

        }catch(\Exception $exception){
            mylog('800005-ios_notify-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit(json_encode(['code'=>0,'msg'=>'异常']));

        }
        
    }
   
    public function order()
    {
        parent::order();
        $data = [
            'order_id'=>$this->order_array['id'],
            'amount'=>$this->order_array['amount'],
            'goods_id'=>$this->order_array['goods_id'],
            'goods_name'=>$this->order_array['goods_name'],
        ];
        $return['code'] = 'success';
        $return['data'] = $data;
        putsuccess($return);
    }
    
    
    public function notify()
    {
        $params = Request::instance()->param();
        mylog($params);

        try{
            $html = $this->acurl(str_replace(' ',"+", $params['receiptData']));
            $data = json_decode($html,true);
            if($data['status'] != 0){
                throw new Exception('苹果返回失败');
            }
            $tradelog = (new \app\home\model\TradeLog)->where(['id'=>$params['order_id']])->find();
            if(!$tradelog){
                throw new Exception('未找到订单');
            }
            
            //判断计费点
            if(empty($data['receipt']['in_app'][0]['product_id'])){
                throw new Exception('苹果返回product_id未找到');
            }
            

            $product_id = $data['receipt']['in_app'][0]['product_id'];
            //效验金额
            // $BillingPoint = BillingPoint::getBillingPointById($product_id);
            $CfgIOS = BillingPoint::CfgIOS($product_id);
            if(!$CfgIOS){
                throw new Exception('未找到改product_id配置信息');
            }
            if ($CfgIOS['OddPrice'] != $tradelog['amount']){
                throw new Exception('订单金额和配置金额不一致');
            }
            if ($tradelog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800004 订单已经处理过了 订单id".$tradelog['id']);
                exit(json_encode(['code'=>1,'msg'=>'']));
            }
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradelog) == false){
                throw new \Exception('notifyProcess false');
            }

            exit(json_encode(['code'=>1,'msg'=>'']));
        }catch (\Exception $exception){
            mylog('800005-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit(json_encode(['code'=>0,'msg'=>'异常']));
        }
       
    }

   
    //curl【模拟http请求】
    function acurl($receipt_data, $sandbox=0){
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS);
        // $POSTFIELDS = '{"receipt-data":"'.$receipt_data."}";
        //正式购买地址
        $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
        //沙盒购买地址
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
        $url = $sandbox ? $url_sandbox : $url_buy;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        mylog($result);
        return $result;
    }


}
